<?php

namespace App\Models\Home;

use Illuminate\Database\Eloquent\Model;

class PositionClass extends Model
{
    protected $table = 'position_class';
    protected $guarded = [];

    /**
     * getTree无限递归函数
     * @param $data
     * @param $field_id
     * @param $field_pid
     * @param int $pid
     * @return array
     * @fillable 变量，保存子集数据
     */
    public function getTree($data, $field_id, $field_pid, $pid = 0) {
        $arr = array();
        foreach ($data as $k=>$v) {
            if ($v->$field_pid == $pid) {
                $arr[$k] = $v;
                $arr[$k]['member'] = self::getTree($data, $field_id, $field_pid, $v->$field_id );
            }
        }
        return $arr;
    }

    public function getTreeList($opt=array()){
        $query = self::orderBy('sort', 'desc');

        if (!empty($opt)){
            foreach ($opt as $k => $v){
                if(is_array($v) && $v[1]){
                    $query = $query->where($k,$v[0],$v[1]);
                }elseif(!is_array($v) && $v !== false){
                    $query = $query->where($k,$v);
                }
            }
        }

        $list = $query->get();

        return self::getTree($list,'id','pid');
    }

    public function getOne($id){

        $obj = self::where('status', 1)->find($id);

        return $obj;
    }

}
